import validate from 'wechat-validate'
const app = getApp()
Page({
  // 通过 behaviors 注入 validate 方法
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
  },
  rules: {
    mobile: [
      { required: true, message: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
    ],
    code: [
      { required: true, message: '请输入验证码' },
      { pattern: /^\d{6}$/, message: '验证码格式不正确' },
    ],
  },
  countDownChange(ev) {
    // console.log(ev.detail)
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 点击获取验证码按钮
  async startCountDown() {
    // 1. 校验手机号的合法性
    const { valid, message } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    // 2.开启倒计时
    this.setData({ countDownVisible: true })
    // 3. 发送验证码
    const { code } = await wx.http.get('/code', { mobile: this.data.mobile })
    // 4. 提示
    if (code !== 10000) return wx.utils.toast('验证码发送失败, 请重试')
    wx.utils.toast('验证码已发送')
  },
  onLoad({ returnURL }) {
    // console.log(returnURL)
    this.setData({ returnURL })
  },
  // 登录
  async login() {
    // 1. 预校验
    if (!this.validate()) return
    // 2. 发送登录的请求
    const res = await wx.http.post('/login', { mobile: this.data.mobile, code: this.data.code })
    // 3. 提示
    if (res.code !== 10000) return wx.utils.toast('登录失败')
    // 4. 存储token信息
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    // 5. 跳转
    if (this.data.returnURL) {
      if (this.data.returnURL === '/pages/index/index' || this.data.returnURL === '/pages/my/index') {
        wx.switchTab({
          url: this.data.returnURL,
        })
      } else {
        wx.redirectTo({
          url: this.data.returnURL,
        })
      }
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    }
  },
})
